// You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build
let _Vue = null
export default class VueRouter {
  static install (Vue) {
    // 1.判断当前插件是否已经被安装
    // 2.把Vue构造函数记录到全局变量
    // 3.把创建Vue实例时候传入的router对象注入到Vue实例上
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    _Vue = Vue
    _Vue.mixin({
      beforeCreate () {
        // 判断是否有router
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      }
    })
  }

  // 构造函数
  constructor (options) {
    this.options = options
    this.mode = options.mode || 'hash'
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
    this.init()
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  createRouteMap () {
    // 编译所有的路由规则，把路由规则解析成键值对的形式，存储到routeMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    const self = this
    // router-link 改变地址栏的路径 不发送请求（即不刷新页面）
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template模板是转换成render汗水
      // template: '<a :href="to"><slot></slot></a>'
      render (h) {
        // 三个参数
        // 标签的名字 对象的属性 子元素
        return h(
          'a',
          {
            // 设置的是dom对象的属性，需要添加在attrs里面
            attrs: {
              href: self.mode === 'hash' ? '#' + this.to : this.to
            },
            on: {
              click:
                self.mode === 'hash' ? this.clickHashHandler : this.clickHandler
            }
          },
          [this.$slots.default]
        )
      },
      methods: {
        clickHandler (e) {
          history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        },
        clickHashHandler (e) {
          this.$router.data.current = this.to
        }
      }
    })

    Vue.component('router-view', {
      // 找当前路由地址
      props: {},
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  initEvent () {
    const eventType = this.mode === 'hash' ? 'hashchange' : 'popstate'
    const handler =
      this.mode === 'hash' ? this.hashCurrent : this.historyCurrent
    window.addEventListener(eventType, handler.bind(this))
  }

  historyCurrent () {
    this.data.current = window.location.pathname
  }

  hashCurrent () {
    const href = window.location.href
    const index = href.indexOf('#')
    if (index < 0) return '/#/'
    this.data.current = href.slice(index + 1)
  }
}
